var gulp=require("gulp");
var imagemin=require("gulp-imagemin");
var pngquant=require('imagemin-pngquant');
var spritesmith=require('gulp.spritesmith');
var minimist=require('minimist');
var buffer = require('vinyl-buffer');
var csso = require('gulp-csso');
var rename = require("gulp-rename");
var replace = require("gulp-replace");
var merge = require('merge-stream');
// var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var sass = require('gulp-ruby-sass'); 
var webserver = require('gulp-webserver');

var uglify = require('gulp-uglify'); // js压缩
var minifyCss = require('gulp-minify-css'); 

var concat = require("gulp-concat"); // 文件合并
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');

var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
gulp.task('minify-css', function() {
  return gulp.src(['./build/20160307whzf/css/animate.min.css','./build/20160307whzf/css/20160307whzf.css'])
    .pipe(minifyCss())
    .pipe(concat('lib.css'))
    .pipe(gulp.dest('./build/20160307whzf/dist/css'));
});
gulp.task('script', function() {
  return gulp.src(['./build/20160307whzf/js/index.js']) // 指明源文件路径、并进行文件匹配
    .pipe(uglify({ preserveComments:'some' })) // 使用uglify进行压缩，并保留部分注释
    .pipe(concat('lib.js'))
    .pipe(gulp.dest('./build/20160307whzf/dist/js')); // 输出路径
});
gulp.task('whzf',['minify-css','script']);

gulp.task('testImagemin',function(){
	return gulp.src('./build/'+options.path+'/images/*.png')
		    .pipe(imagemin({
            progressive: true,
            optimizationLevel :2,
            use: [pngquant()]
        }))
		   .pipe(gulp.dest('./build/'+options.path+'/images/sprite'));

});
gulp.task('sprite',function(){
 // Generate our spritesheet
  var spriteData = gulp.src('./build/'+options.path+'/images/sprites/icon*.png').pipe(spritesmith({
    imgName: 'sprite.png',
    cssName: 'sprite.css',
    cssFormat: 'css',
    cssVarMap: function(item) {
       // if (item.name.indexOf('-hover') !== -1) {
    	  //  console.log(item.name,'替换前');
       //     item.name= item.name.replace('-hover', ':hover');
    	  //  console.log(item.name,'替换后');
       // }
   }
  }));

  // Pipe image stream through image optimizer and onto disk
  var imgStream = spriteData.img
    // DEV: We must buffer our stream into a Buffer for `imagemin`
    .pipe(buffer())
    .pipe(imagemin())
    .pipe(gulp.dest('./build/'+options.path+'/images/sprites'));

  // Pipe CSS stream through CSS optimizer and onto disk
  var cssStream = spriteData.css
    .pipe(csso())
    .pipe(gulp.dest('./build/'+options.path+'/css'));

  // Return a merged stream to handle both `end` events
  return merge(imgStream, cssStream);

});
// gulp.task('default',['imagemin','sprite']);
var options=minimist(process.argv.slice(2));
// 键入格式为
gulp.task('ScssFileHandler',['AssetCopy'],function(){
	 var scssRenameAndReplace=  gulp.src(options.timestamppath+'/sass/layout.scss')
								.pipe(rename(options.date+'.scss'))
								.pipe(replace('//SASS',options.finaleScssStr))
								.pipe(gulp.dest(options.timestamppath+'/sass/'))
								;						
	return  scssRenameAndReplace;

});
gulp.task('IndexFileHandler',['AssetCopy'],function(){
	var indexhtmlReplace=gulp.src(options.timestamppath+'/html/index.html')
							.pipe(replace('EMMET',options.finaleEmmetStr))
							.pipe(gulp.dest(options.timestamppath+'/html/'));							
	return indexhtmlReplace;

});

gulp.task('AssetCopy',function(cb){
	var tasktype=options.type;
	var jsonpath='/webjson/'+options.path+'.json';
	if(tasktype&&jsonpath){
		try{
   	   		 var jsonObj=require(__dirname+jsonpath);
    	 } 
    	 catch (ex) {
    	 	console.log(ex);
    	 }
		var jte=new JsonToEmmet(jsonObj);
		jte.init();
		var date=new Date();
		var timestamp=date.getTime();
		options.date=jsonObj.date;
		options.timestamppath='./build/'+jsonObj.date+'_'+timestamp;
		return gulp.src(['./lib/zeyuan/*/*','!./lib/zeyuan/css/*'])
			   .pipe(gulp.dest(options.timestamppath))
			   ;
			   
		
	}else{
		console.log('无法获取到正确参数 任务停止');
	return false;
	} 
});

gulp.task('mySass', function () {
	 var processors = [
        autoprefixer({browsers: ["Android 4.1", "iOS 7.1", "Chrome > 31", "ff > 31", "ie >= 9"]}),
        // cssnano(),
    ];
      sass('./build/'+options.path+'/sass/'+options.path+'.scss', {sourcemap: false,style: 'compact' }) // 指明源文件路径、并进行文件匹配（style: 'compressed' 表示输出格式）
          .on('error', function (err) {
               console.error('Error!', err.message); // 显示错误信息
          })
		     // For file sourcemaps
		    .pipe(sourcemaps.write('./'))
		    .pipe(postcss(processors))
        .pipe(gulp.dest('./build/'+options.path+'/css/'))
        .pipe(livereload()); // 输出路径
});
gulp.task('default',['ScssFileHandler','IndexFileHandler']);
gulp.task('webserver', function() {
  gulp.src( '.' ) // 服务器目录（./代表根目录）
  .pipe(webserver({ // 运行gulp-webserver
  	host:'localhost',
  	port:'9000',
  	'directoryListing':true,
    livereload: true, // 启用LiveReload
    root: 'gulptask/build/'+options.path+'/', // 制定工作目录
    open: 'build/'+options.path+'/html/index.html' // 服务器启动时自动打开网页
  }));
});
gulp.task('mySprite', function () {
 // Generate our spritesheet
  var spriteData = gulp.src('./build/'+options.path+'/images/sprites/icon*.png').pipe(spritesmith({
     imgName: 'sprite.png',
     cssName: 'sprite.scss',
     cssFormat: 'scss',
	  algorithm: 'binary-tree',
	  padding: 8,
	  cssTemplate:'scss.template.mustache'

  }));

  // Pipe image stream through image optimizer and onto disk
  var imgStream = spriteData.img
    // DEV: We must buffer our stream into a Buffer for `imagemin`
    .pipe(buffer())
    .pipe(imagemin())
    .pipe(gulp.dest('./build/'+options.path+'/images/sprites'));

  // Pipe CSS stream through CSS optimizer and onto disk
  var cssStream = spriteData.css
    .pipe(gulp.dest('./build/'+options.path+'/sass'));

  // Return a merged stream to handle both `end` events
  return merge(imgStream, cssStream);

});
gulp.task('myHtml', function () {
    return gulp.src('./build/'+options.path+'/html/*.html')
    .pipe(livereload());
});
gulp.task('watch',function(){
		console.log('监听路径:build/',options.path);
	if(!options.path) return false;
	livereload.listen();
	gulp.watch('build/'+options.path+'/html/*',['myHtml'],function(){
		console.log("html has changed"); 
	});
	gulp.watch('build/'+options.path+'/sass/*.scss',['mySass']);
	gulp.watch('build/'+options.path+'/images/sprites/*',['mySprite']);

});
gulp.task('live',['webserver','watch'],function(){

});


/*---------------------以下为emmet生成对象-----------------------------*/
var JsonToEmmet=function(jsonObj){
	var _jsonObj=jsonObj;
	this.init=function(){
		options.finaleEmmetStr=getEmmetStr();
		options.finaleScssStr=getScssStr();
		// console.log(options);
	}
	/*	
	遍历对象传入的jsonObj 
	如果key值中含有con代表为一个container
	*/
	function getScssStr(){
		var finaleScssStr='';
	    var initsass='';
        // console.log('initsass','-------------');
        for(por in _jsonObj){
        	if(por.indexOf('con')>-1){
         	 	for(node in _jsonObj[por]){
         		    var nodeValue;
         	   		nodeValue=_jsonObj[por][node].split(','); 
         	   		initsass+='\t.'+nodeValue[0]+'\t{\n\t\t@include wah('+nodeValue[1]+'px,'+nodeValue[2]+'px,none);\n\t}\n';
         	   }
        	}
        }
         finaleScssStr =initsass.replace(/>/g,' .');
         return finaleScssStr;
	}	
	/*	
	遍历对象传入的jsonObj 
	如果key值中含有con代表为一个container
	*/
	function getEmmetStr(){
		var finaleEmmetStr='';
		var length=1;
		for(var por in _jsonObj){
			if(por.indexOf('con')>-1){
				// console.log(_jsonObj[por]);
			finaleEmmetStr +='.con.con'+length+'>.wrap>'+handOneContainer(_jsonObj[por])+'\n';
			length++;
			}
		}
		return finaleEmmetStr;
	}
	/*
	处理传入的container对象
	@obj Array
	传入格式为.L1>.C2-1,200,300  即对应页面的每个最小单元格 	
	*/
	function handOneContainer(obj){
		var pathList=[];
		// console.log(obj);
		for(var por in obj){
			pathList.push(obj[por].split(',')[0]);
		}
		// console.log(pathList);
		var nodeArr=[];
		pathList.forEach(function(e,i){
			var initArr=e.split('>');
			var levelIndexArr=[]
			levelIndexArr=initArr.map(function(obj){
				for(var i=6;i>0;i--){
					if(obj.indexOf('-'+i)>-1||obj.indexOf('L'+i)>-1){
						return 2*i-1;
						break;
					}
				}
			});
			try{
				initArr.forEach(function(e,index){
					var lev0=levelIndexArr[0];
					var lev1=levelIndexArr[1];
					var lev2=levelIndexArr[2];
					var lev3=levelIndexArr[3];
					var lev4=levelIndexArr[4];
					var lev4=levelIndexArr[5];
					var tempIndex=levelIndexArr[index];
					// console.log('层级',index,lev0,lev1,lev2,lev3);
					if(index==0){
						if(!nodeArr[tempIndex])
	                        nodeArr.push(e,[]); 
					}else if(index==1){
						if(!nodeArr[lev0][tempIndex])
	                        nodeArr[lev0].push(e,[]); 
					}else if(index==2){
						if(!nodeArr[lev0][lev1][tempIndex])
	                        nodeArr[lev0][lev1].push(e,[]); 
					}else if(index==3){
						if(!nodeArr[lev0][lev1][lev2][tempIndex])
	                        nodeArr[lev0][lev1][lev2].push(e,[]); 
					}else if(index==4){
						if(!nodeArr[lev0][lev1][lev2][lev3][tempIndex])
	                        nodeArr[lev0][lev1][lev2][lev3].push(e,[]); 
					}else if(index==5){
						if(!nodeArr[lev0][lev1][lev2][lev3][lev4][tempIndex])
	                        nodeArr[lev0][lev1][lev2][lev3][lev4].push(e,[]); 
					}
				});
			}catch (ex) {
    	 		console.log(ex,'可能json文件item有重名');
    	 	}
			
			// console.log(nodeArr.toString(),'最终的节点',levelIndexArr,initArr);
		});
		var finalestr=handDimsArray(nodeArr,'');
		// console.log(finalestr,'最终语句');
		return finalestr; 
	}
    /*
    @arr Array
	处理一个类似于数结构的多维数组 转为为emmet
	通过递归调用 如果数组的元素依旧是数组 则递归调用
	拼接emmet字符串时  如果同级数组元素前一个元素有子元素的话 则本元素做升级处理即 添加^

    */
	function handDimsArray(arr){
		// console.log('这次传入的参数是',arr,str);
		var str ='(';
		arr.forEach(function(e,i){
			if(e instanceof Array&&e.length>1){
				// console.log(e,'这是个数组');
				str+='>';
				
				str+=handDimsArray.call(this,e);
			}else if(arr[i-1] instanceof Array&&arr[i-1].length>1){
				str+=i>0?'+^.'+e:'.'+e;
			}else if(e.length>1){
				str+=i>0?'+.'+e:'.'+e;
			}
		});
		str+=')';
		return str;
		// console.log(str,'最终语句');
	}
}



























